package com.jzoom.zoom.admin.interceptors;

import com.jzoom.zoom.common.codec.HashStr;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class SignUtil {

    public static final String rand_str = "rand_str";
    public static final String time = "time";
    public static final String sign="sign";

    /**
	 * 准备数据
	 * @param map	数据
	 * @param appid	appid
	 * @param key	秘钥
	 * @return
	 */
	public static TreeMap<String, Object> prepareData(TreeMap<String, Object> map,String appid,String key){
		map.put("appid", appid);
		map.put("rand_str", HashStr.md5(String.valueOf(System.nanoTime() * Math.random())));
		map.put("time", System.currentTimeMillis()/ 1000);
		String sign = getSign(map, key);
		map.put("sign", HashStr.md5(sign));
		return map;
	}
	
	/**
	 * 对返回结果进行验证
	 * @param json
	 * @param key
	 * @return
	 */
	public static boolean validate(Map<String, Object> json,String key){
		String sign = (String)json.get(SignUtil.sign);
		if(sign==null){
			return false;
		}
		json.remove(SignUtil.sign);
		if(!json.containsKey(SignUtil.rand_str)){
			return false;
		}
		if(!json.containsKey(SignUtil.time)){
			//判断时间(略)
			return false;
		}
		
		String newSign = SignUtil.getSign(new TreeMap<String, Object>(json),key);
		String countSing =  HashStr.md5(newSign);
		if(sign.equals(countSing)){
			return true;
		}
		
		//LogUtil.log("待加密数据:%s 计算签名：%s 上送签名:%s", newSign, countSing, sign);
		
		return false;
	}
	
 	private static String getSign(TreeMap<String, Object> data,String key) {
		//先移除sign字段
		data.remove(SignUtil.sign);
		
		StringBuilder sb = new StringBuilder();
		boolean first = true;
		for (Entry<String, Object> entry : data.entrySet()) {
		    Object value = entry.getValue();
		    /// 集合类型不参与签名
		    if(value instanceof Iterable){
		        continue;
            }
            /// Map 也不参与
            if(value instanceof Map){
		        continue;
            }

            /// array类型?不要使用
            if(value!=null && value.getClass().isArray()){
		        throw new RuntimeException("请不要在参数中使用array");
            }

			if(first){
				first = false;
			}else{
				sb.append("|");
			}
			sb.append(entry.getKey()).append("=").append(value);
		}
		sb.append(key);
		
		
		return sb.toString();
	}
}
